"use client"

import { createContext, useContext, useState, useEffect, ReactNode } from "react"
import { useRouter } from "next/navigation"
import { useToast } from "@/components/ui/use-toast"
import Cookies from 'js-cookie'

interface User {
  id: string
  name: string
  email: string
}

interface AuthContextType {
  user: User | null
  token: string | null
  isLoading: boolean
  isAuthenticated: boolean
  login: (email: string, password: string) => Promise<void>
  register: (name: string, email: string, password: string) => Promise<void>
  logout: () => void
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  const [token, setToken] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const router = useRouter()
  const { toast } = useToast()

  // 初始化时检查用户是否已登录
  useEffect(() => {
    const checkAuth = () => {
      try {
        const storedToken = localStorage.getItem("token")
        const isLoggedIn = localStorage.getItem("isLoggedIn") === "true"
        
        if (isLoggedIn && storedToken) {
          setToken(storedToken)
          const userData = localStorage.getItem("user")
          if (userData) {
            setUser(JSON.parse(userData))
          }
        }
      } catch (error) {
        console.error("Auth check error:", error)
      } finally {
        setIsLoading(false)
      }
    }

    checkAuth()
    // 空依赖数组 [] 确保这个效果只在组件挂载时执行一次
  }, [])

  // 登录方法
  const login = async (email: string, password: string) => {
    setIsLoading(true)
    try {
      console.log("开始登录请求:", { email })
      
      const response = await fetch('/api/auth', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email, password }),
      })
      
      console.log("登录请求状态:", response.status)
      
      const data = await response.json()
      console.log("登录响应:", data)
      
      if (!response.ok) {
        throw new Error(data.error || '登录失败')
      }
      
      if (!data.success) {
        throw new Error(data.error || '登录失败')
      }
      
      // 保存用户信息和令牌
      localStorage.setItem("isLoggedIn", "true")
      localStorage.setItem("token", data.token)
      localStorage.setItem("user", JSON.stringify(data.user))
      
      // 设置Cookie，用于服务端验证
      Cookies.set('isLoggedIn', 'true', { expires: 7 })
      
      setUser(data.user)
      setToken(data.token)
      
      // 显示成功提示
      toast({
        title: "登录成功",
        description: `欢迎回来，${data.user.name}！`,
        variant: "default",
      })
      
      router.push("/")
    } catch (error) {
      console.error("登录失败:", error)
      
      // 显示错误提示
      toast({
        title: "登录失败",
        description: error instanceof Error ? error.message : "邮箱或密码错误，请重试",
        variant: "destructive",
      })
      throw error
    } finally {
      setIsLoading(false)
    }
  }

  // 注册方法
  const register = async (name: string, email: string, password: string) => {
    setIsLoading(true)
    try {
      console.log("开始注册请求:", { name, email })
      
      const response = await fetch('/api/auth', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, email, password }),
      })
      
      console.log("注册请求状态:", response.status)
      
      const data = await response.json()
      console.log("注册响应:", data)
      
      if (!response.ok) {
        throw new Error(data.error || '注册失败')
      }
      
      if (!data.success) {
        throw new Error(data.error || '注册失败')
      }
      
      // 显示成功提示
      toast({
        title: "注册成功",
        description: "您的账号已创建成功，请登录",
        variant: "default",
      })
      
      router.push("/login")
    } catch (error) {
      console.error("注册失败:", error)
      
      // 显示错误提示
      toast({
        title: "注册失败",
        description: error instanceof Error ? error.message : "创建账号时出现问题，请重试",
        variant: "destructive",
      })
      throw error
    } finally {
      setIsLoading(false)
    }
  }

  // 登出方法
  const logout = () => {
    localStorage.removeItem("isLoggedIn")
    localStorage.removeItem("token")
    localStorage.removeItem("user")
    Cookies.remove('isLoggedIn')
    setUser(null)
    setToken(null)
    
    // 显示登出成功提示
    toast({
      title: "退出成功",
      description: "您已安全退出登录",
      variant: "default",
    })
    
    router.push("/")
  }

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        isLoading,
        isAuthenticated: !!user,
        login,
        register,
        logout
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
} 